/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.controller;


import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.entity.LoginResponse;
import io.renren.modules.app.entity.ResidentEntity;
import io.renren.modules.app.form.RegisterForm;
import io.renren.modules.app.service.ResidentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 注册
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP驻厂登录接口")
public class ResidentLoginController {
    @Autowired
    private ResidentService residentService;

    @PostMapping("reslogin")
    @ApiOperation("驻厂登录")
    public ResponseEntity<LoginResponse> login(@RequestBody RegisterForm form) {
        // 表单校验
        ValidatorUtils.validateEntity(form);
        ResidentEntity existingUser = residentService.queryByIphoneAndId(form.getIPhone(), form.getID());
        LoginResponse response = new LoginResponse();
        if (existingUser != null) {
            // 如果找到了已存在的用户，则更新openid并返回成功响应
            residentService.updateOpenIdByIphoneAndId(form.getOpenId(), form.getIPhone(), form.getID());
            response.setCode(0);
            response.setMessage("登录成功");
            response.setIsLogin(true);
            response.setData(existingUser);
        } else {
            // 如果没有找到用户，则返回错误响应
            response.setCode(404);
            response.setIsLogin(false);
            response.setMessage("用户未找到");
        }
        return ResponseEntity.ok(response);
    }
    @PostMapping("openidlogin")
    @ApiOperation("OpenID登录")
    public ResponseEntity<LoginResponse> openidLogin(@RequestParam String openId) {
        // 表单校验

        ResidentEntity existingUser = residentService.queryByOpenid(openId);
        LoginResponse response = new LoginResponse();
        if (existingUser != null) {
            // 如果找到了已存在的用户，则返回成功响应
            response.setCode(0);
            response.setMessage("登录成功");
            response.setIsLogin(true);
            response.setData(existingUser);
        } else {
            // 如果没有找到用户，则返回错误响应
            response.setCode(404);
            response.setIsLogin(false);
            response.setMessage("用户未找到");
        }
        return ResponseEntity.ok(response);
    }
}
